# -*- coding: utf-8 -*-
import KBEngine
from KBEDebug import *
import time
from AVATAR_INFOS import TAvatarInfos

class Account(KBEngine.Proxy):
	def __init__(self):
		KBEngine.Proxy.__init__(self)
		self.activeAvatar = None
		self.relogin = time.time()

	def onTimer(self, id, userArg):
		"""
		KBEngine method.
		使用addTimer后， 当时间到达则该接口被调用
		@param id		: addTimer 的返回值ID
		@param userArg	: addTimer 最后一个参数所给入的数据
		"""
		DEBUG_MSG(id, userArg)

	def onClientEnabled(self):
		"""
		KBEngine method.
		该entity被正式激活为可使用， 此时entity已经建立了client对应实体， 可以在此创建它的
		cell部分。
		"""
		INFO_MSG("account[%i] entities enable. entityCall:%s" % (self.id, self.client))

	def onLogOnAttempt(self, ip, port, password):
		"""
		KBEngine method.
		客户端登陆失败时会回调到这里
		"""
		INFO_MSG(ip, port, password)
		return KBEngine.LOG_ON_ACCEPT

	def onClientDeath(self):
		"""
		KBEngine method.
		客户端对应实体已经销毁
		"""
		if self.activeAvatar:
			self.activeAvatar.accountEntity = None
			self.activeAvatar = None
		DEBUG_MSG("Account[%i].onClientDeath:" % self.id)
		self.destroy()

	def _onAvatarSaved(self, success, avatar):
		INFO_MSG('Account _onAvatarSaved')
		if self.isDestroyed:
			if avatar:
				avatar.destroy(True)
			return
		# 如果是没有角色
		if success:
			self.character = avatar.databaseID
			self.writeToDB()

		avatar.destroy()
		if self.client:
			self.client.onReqAvatar(self.character)

	def _onAvatarCreated(self, baseRef, dbid, wasActive):
		INFO_MSG('Account _onAvatarCreated')
		if wasActive:
			ERROR_MSG("Account::_onAvatarCreated (%i): this character i in game now" % self.id)
			return
		if baseRef is None:
			ERROR_MSG("Account::_onAvatarCreated (%i): this character you wanted to created i not exist!" % self.id)
			return
		avatar = KBEngine.entities.get(baseRef.id)
		if avatar is None:
			ERROR_MSG("Account::_onAvatarCreated (%i): when character was created, it died as well!" % self.id)
			return
		if self.isDestroyed:
			ERROR_MSG("Account::_onAvatarCreated (%i): i dead, will the destroy of Avatar!" % self.id)
			avatar.destroy()
			return
		avatar.accountEntity = self
		self.activeAvatar = avatar
		self.giveClientTo(avatar)

	def reqAvatar(self):
		DEBUG_MSG("Account[%i].reqAvatar:" % self.id)
		self.client.onReqAvatar(self.character)

	def reqCreateAvatar(self, job, sex, nickName):
		props = {
			"name"	: nickName,
			"_profession"	: job,
			"_sex"	: sex,
		}

		avatar = KBEngine.createEntityLocally('Avatar', props)
		if avatar:
			avatar.writeToDB(self._onAvatarSaved)

	def selectAvatar(self):
		if self.character == 0:
			return
		if self.activeAvatar is None:
			KBEngine.createEntityFromDBID("Avatar", self.character, self._onAvatarCreated)



